package com.blackcat.v1.core;


import com.blackcat.v1.*;
import com.blackcat.v1.connector.HttpResponse;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Slf4j
public class SimpleContextValve implements Valve, Contained {

    private Container container;

    public String getInfo() {
        return this.getClass().getName();
    }

    public void invoke(Request request, Response response, ValveContext context) throws IOException, ServletException {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        if (requestURI.startsWith("/servlet")) requestURI = requestURI.replace("/servlet","");
        if (requestURI.startsWith("/")) requestURI = requestURI.substring(1);
        SimpleWrapper wrapper = (SimpleWrapper) getContainer().findChild(requestURI);
        if(wrapper == null){
            ((HttpResponse) response).getWriter().write("no servlet");
            ((HttpResponse) response).finishResponse();
        }else{
            wrapper.invoke(request, response);
        }

    }

    public Container getContainer() {
        return container;
    }

    public void setContainer(Container container) {
        this.container = container;
    }
}
